using System;
using System.Collections.Generic;
using System.Linq;
using YouVisio.Silverlight.TextDiff.Extensions;

namespace YouVisio.Silverlight.TextDiff
{
    public class TextPartFinder : ITextPartFinder
    {

        public TextPartFinder(ITextDiffFactory factory, IDiffAnalyser analyser)
        {
            DiffAnalyser = analyser;
            Factory = factory;
        }

        protected IDiffAnalyser DiffAnalyser { get; private set; }
        protected ITextDiffFactory Factory { get; private set; }

        public List<TextPart> Find(string left, string right)
        {
            // see if the strings are the same
            if (left == null) left = String.Empty;
            if (right == null) right = String.Empty;
            if(left.Length == right.Length && left == right)
            {
                var lines = left.SplitLines();
                return new List<TextPart> { new TextPart(Operation.Equal, lines, lines) };
            }
//TextPart end = null;
            var allTextParts = new List<TextPart>();
            // see if the strings share same beginning
//var tuple = left.SameBeginningCompleteLines(right);
//if (tuple.Item1 != "")
//{
//    var startLines = tuple.Item1.SplitLines();
//    var start = new TextPart(Operation.Equal, startLines, startLines);
//    allTextParts.Add(start);
//    left = tuple.Item2;
//    right = tuple.Item3;
//    if(left == "")
//    {
//        if (right == "") return allTextParts;
//        allTextParts.Add(new TextPart(Operation.Insert, null, right.SplitLines()));
//        return allTextParts;
//    }
//    if(right == "")
//    {
//        allTextParts.Add(new TextPart(Operation.Delete, left.SplitLines(), null));
//        return allTextParts;
//    }
//}
//// see if the strings share the same ending
//tuple = left.SameEndingCompleteLines(right);
//if (tuple.Item3 != "")
//{
//    var endLines = tuple.Item3.SplitLines();
//    end = new TextPart(Operation.Equal, endLines, endLines);
//    left = tuple.Item1;
//    right = tuple.Item2;
//}

            var info = StringHashInfo.CreateForLines(left, right);

            var leftRetriever = Factory.GetNewInt32PartsRetriever();
            leftRetriever.Source = info.LeftListHashes.ToArray();
            var rightRetriever = Factory.GetNewInt32PartsRetriever();
            rightRetriever.Source = info.RightListHashes.ToArray();
            var diffParts = DiffAnalyser.Analyse(EqualityComparer<int>.Default, leftRetriever, rightRetriever);

            allTextParts = info.FoldTextParts(allTextParts, diffParts, (acc, tp) => { acc.Add(tp); return acc; });
//if (end != null)
//{
//    allTextParts.Add(end);
//}
            return allTextParts;
        }

    }
}
